<template>
  <div class="link-container">
    <div class="contract">
      <div v-if="!isChangeOrder" class="sub-title-container">
        <div v-if="type===2 && title === '' && subTitle && subTitle!==''" class="sub-title">{{ subTitle }}</div>
        <div v-if="title" style="display:flex;align-items:center;">
          <Title :title="title" :font-size="titleSize" />
          <IconAmountLayout v-if="type===2 && selectData && selectData.length && showInvoiceAmountTotal" :amount="invoiceAmountTotal?invoiceAmountTotal/100: invoiceAmountTotal" amount-text="有效发票金额" />
          <slot name="title-after" />
        </div>
        <div class="ui-col"/>
        <slot name="btn-group" />
        <PlainCreateBtn
          v-if="isEdit && !hideAllOperation"
          :style="relatedContractStyle"
          size="small"
          @click="relatedContractShow(type)">关联{{ type === 1?'合同':'发票' }}</PlainCreateBtn>
      </div>
      <el-table
        v-if="type===1 && selectData && selectData.length > 0"
        :data="handelData(selectData)"
        class="fb-table"
        element-loading-text="加载中..."
        fit
        empty-text="暂无数据">
        <el-table-column align="left" label="项目名称" min-width="150">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.contractName" is-can-click @handelClick="toDetail(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="合同编号" min-width="130">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.contractCode"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="合同日期" width="210">
          <template slot-scope="scope">
            <el-tooltip :open-delay="800" placement="top" effect="dark">
              <div slot="content" style="max-width: 220px; white-space: nowrap; padding: 0 10px;">
                <span v-if="scope.row.contractDate === 1 || scope.row.contractDate === null">{{ scope.row.contractEffectStartDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }} - {{ scope.row.contractEffectEndDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                <span v-else>{{ scope.row.pushTime/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
              </div>
              <div class="line-clamp1">
                <span v-if="scope.row.contractDate === 1 || scope.row.contractDate === null">{{ scope.row.contractEffectStartDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }} - {{ scope.row.contractEffectEndDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                <span v-else>{{ scope.row.pushTime/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="left" label="审批进度" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.reviewProgress || '--' }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="申请人部门" min-width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.department"/>
          </template>
        </el-table-column>
        <el-table-column v-if="!isChangeOrder && !hideAllOperation" align="left" label="操作">
          <template slot-scope="scope">
            <span v-if="!isDisabled && isEdit" class="delete-btn" @click="deleteRelated(scope.$index)">删除</span>
            <span v-else class="delete-btn not-allowed" >删除</span>
          </template>
        </el-table-column>
      </el-table>
      <el-table
        v-if="type===2 && selectData && selectData.length"
        :data="handelData(selectData)"
        class="fb-table"
        element-loading-text="加载中..."
        empty-text="暂无数据">
        <el-table-column align="left" label="发票号码" min-width="160">
          <template slot-scope="scope">
            <span v-if="scope.row.number" class="link ellipsisOne" @click="goInvoice(scope.row)">{{ scope.row.number }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="发票状态" min-width="120">
          <template slot-scope="scope">
            <div v-if="typeof scope.row.invoiceState === 'number'" style="display:flex;align-items:center">
              <div :class="`color-state-${scope.row.invoiceState}`" class="dot"/>
              <div>{{ scope.row.invoiceState | invoiceState }}</div>
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="发票类型" min-width="130">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.invoiceType" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="纳税人名称" min-width="150">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.taxpayerName" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="我方抬头">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.ourTitle" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="申请人">
          <template slot-scope="scope">
            <CheckUserInfo v-if="scope.row.proposer" :label="scope.row.proposer" :user-id="scope.row.proposerId" />
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column align="right" label="含税金额(元)" min-width="150">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.amountFen" :price="scope.row.amountFen / 100" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="开票项目">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.project" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="开票审批" min-width="140">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.approvalNo" is-can-click @handelClick="goIssueInvoiceDetail(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="开票人">
          <template slot-scope="scope">
            <CheckUserInfo v-if="scope.row.issuer" :label="scope.row.issuer" :user-id="scope.row.issuerId" />
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="开票日期" min-width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.invoiceDate">{{ scope.row.invoiceDate | format('YYYY/MM/DD HH:mm') }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column v-if="!isChangeOrder && !hideAllOperation" align="left" label="操作">
          <template slot-scope="scope">
            <span v-if="!isDisabled && isEdit" class="delete-btn" @click="deleteRelated(scope.$index)">删除</span>
            <span v-else class="delete-btn not-allowed" >删除</span>
          </template>
        </el-table-column>
      </el-table>
      <div v-else-if="showEmpty && selectData.length === 0 " class="empty-container">
        <div class="empty-box">
          <img :src="emptyInvoice" alt="empty">
          <div class="empty-text">暂无数据</div>
        </div>

        <!-- <img :src="emptyImg" alt=""> -->
        <!-- <div class="empty-text">{{ type===1?'暂未关联合同，可通过点击关联合同按钮或到合同管理页面新建合同关联至该订单':'暂未关联发票，可通过输入发票编号/号码或到发票管理页面新建合同发票关联至该订单' }}</div> -->
      </div>
    </div>
    <el-row justify="end" type="flex" class="pagination-area">
      <el-pagination
        v-show="selectData.length > 10"
        :current-page="contractPage"
        :page-size="contractPerPage"
        :total="selectData.length"
        :small="showMobile"
        :page-sizes="[10,20, 50, 100, 250, 500]"
        :layout="showMobile ?'prev, pager, next, jumper':'total, prev, pager, next, sizes, jumper'"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-row>
    <!-- 关联合同 -->
    <relatedContract
      ref="showRelatedContract"
      :visible.sync="showRelatedContract"
      is-show-other
      @confirmRelatedContract="confirmRelatedContract"
    />
    <relatedInvoice ref="relatedInvoiceRef" :is-abandon="isAbandon" @confirmRelatedContract="confirmRelatedContract" />
  </div>
</template>

<script>
import emptyImg from '@/assets/empty-data-icon.png';
import emptyInvoice from '@/assets/empty-invoice.png';

import { getList } from '@/api/legal';
import { getInvoiceList } from '@/api/invoice';
import { standardFormatNoHour, format } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import { mapOptions } from '@/filters';
import { encryption } from '@/utils';
import Title from '@/components/Title';
import relatedContract from './relatedContract';
import relatedInvoice from './relatedInvoice';
import options from '@/views/legal/module/options';
import IconAmountLayout from '@/components/Common/IconAmountLayout';

export default {
  components: { Title, relatedContract, relatedInvoice, IconAmountLayout },
  filters: {
    standardFormatNoHour,
    moneyFilter,
    format,
    mapOptions,
    invoiceStatus(num) {
      // 0:执行中, 1: 已完成，2：作废中 3：已作废
      const arr = ['执行中', '已完成', '作废中', '已作废'];
      return arr[num] || '--';
    },
    invoiceState(status) {
      return {
        0: '正数正常',
        1: '正数作废',
        2: '负数正常',
        3: '负数作废'
      }[status] || '--';
    }
    // relatedContractDialog
  },
  props: {
    type: { // type 1:合同 2:发票
      type: Number,
      default: 1
    },
    subTitle: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    titleSize: {
      type: String,
      default: '16px'
    },
    isDisabled: {
      type: Boolean,
      default: false
    },
    hideAllOperation: {
      type: Boolean,
      default: false
    },
    isChangeOrder: {
      type: Boolean,
      default: false
    },
    relatedContractStyle: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: '请选择合同编号/合同名称'
    },
    showEmpty: {
      type: Boolean,
      default: false
    },
    initRequestData: {
      type: Boolean,
      default: false
    },
    isAbandon: { // 是否来源发票作废
      type: Boolean,
      default: false
    },
    showInvoiceAmountTotal: { // 是否展示发票总额
      type: Boolean,
      default: false
    },
    isIssueInvoiceModule: { // 开票申请模块
      type: Boolean,
      default: false
    },
    showMobilePage: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      emptyInvoice,
      contractPage: 1,
      contractPerPage: 10,
      currentPageData: [],
      options,
      emptyImg,
      relatedIds: [],
      relatedContract: [],
      loading: false,
      relatedOptions: [],
      selectData: [],
      showRelatedContract: false// 关联合同弹窗
    };
  },
  computed: {
    invoiceAmountTotal() {
      const selectData = this.selectData;
      let total = null;
      if (selectData && selectData.length) {
        selectData.forEach(i => {
          if ((i.amountFen || i.amountFen === 0) && i.status === 1) {
            total = (total || 0) + i.amountFen;
          }
        });
      }
      return total;
    },
    showMobile() {
      return !!(this.showMobilePage);
    }
  },
  created() {
    if (!this.isDisabled && this.initRequestData && this.isEdit) {
      this.optionsList('');
    }
  },
  methods: {
    setDefault(list) {
      if (list && list.length > 0) {
        this.selectData = JSON.parse(JSON.stringify(list));
        this.relatedIds = list.map(i => i.id);
        this.relatedOptions = JSON.parse(JSON.stringify(list));
      } else {
        this.selectData = [];
        this.relatedIds = [];
        this.relatedOptions = [];
      }
    },
    handleSizeChange(val) {
      this.contractPerPage = val;
    },
    handleCurrentChange(val) {
      this.contractPage = val;
    },
    // 本地分页
    handelData(data) {
      return data.slice((this.contractPage - 1) * this.contractPerPage, this.contractPage * this.contractPerPage);
    },
    async optionsList(query) {
      // type 1:合同 2:发票
      // if (query !== '') {
      this.loading = true;
      try {
        const params = {
          keyword: query,
          page: 1,
          perPage: 50
        };
        if (this.type === 1) {
          params.process = 4;
          const res = await getList(params);
          this.loading = false;
          this.relatedOptions = res.data.items;
          return false;
        }
        if (this.type === 2) {
          const res = await getInvoiceList(params);
          this.loading = false;
          this.relatedOptions = res.data.items;
          return false;
        }
      } catch (error) {
        console.log(error);
      }
      // } else {
      //   this.relatedOptions = [];
      // }
    },
    formatOption(value) {
      if (value.length > 0) {
        this.selectData = this.selectData.filter(i => {
          return value.includes(i.id);
        });
        const ids = this.selectData.map(i => i.id);
        const selectData = this.relatedOptions.map(i => {
          if (value.includes(i.id) && !ids.includes(i.id)) {
            return i;
          }
        }).filter(i => !!i);
        this.selectData = this.selectData.concat(selectData);
      } else {
        this.selectData = [];
      }
      this.$emit('changeSelect', this.selectData);
    },
    deleteRelated(index) {
      const idx = index + ((this.contractPage - 1) * this.contractPerPage);
      this.relatedIds.splice(idx, 1);
      this.selectData.splice(idx, 1);
      this.$emit('changeSelect', this.selectData);
      if (((this.contractPage - 1) * this.contractPerPage) >= this.selectData.length) {
        this.contractPage = 1;
      }
    },
    relatedContractShow(type) {
      // type 1:合同 2:发票
      if (type === 1) {
        this.showRelatedContract = true;
        this.$refs['showRelatedContract'].init();
        this.$refs['showRelatedContract'].initSelectData(this.selectData);
      } else {
        this.$refs['relatedInvoiceRef'].openDialog(this.selectData);
      }
    },
    // 合同关联
    confirmRelatedContract(data) {
      if (this.type === 1) { // 合同
        this.showRelatedContract = false;
      } else {
        this.$refs['relatedInvoiceRef'].closeDialog();
      }
      this.contractPage = 1;
      this.selectData = data;
      this.$emit('changeSelect', data);
    },
    // 跳转合同详情
    toDetail(row) {
      const routeUrl = this.$router.resolve({
        name: 'contractDetail',
        params: { id: encryption(row.id) },
        query: {
          processId: encryption(row.processId)
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    // 跳转发票详情
    goInvoice(row) {
      const routeUrl = this.$router.resolve({
        name: 'invoiceDetail',
        params: { id: row.id }
      });
      window.open(routeUrl.href, '_blank');
    },
    goInvoiceAbandon(item) {
      if ((item.status === 2 || item.status === 3) && item.abandonId && item.abandonProcessId && !this.isAbandon) {
        // 作废中、已作废，新窗口打开作废审批详情
        const routeUrl = this.$router.resolve({
          name: 'invoiceAbandonDetail',
          query: { id: item.abandonId, processId: item.abandonProcessId }
        });
        window.open(routeUrl.href, '_blank');
      }
    },
    goIssueInvoiceDetail(rowData) {
      const { applyId, processId } = rowData;
      if (applyId && processId) {
        const url = this.$router.resolve({
          name: 'issueInvoiceDetail',
          query: {
            issueId: applyId,
            processId: processId
          }
        });
        window.open(url.href, '_blank');
      }
    }
  }
};
</script>

<style lang="scss" scoped>
$state: #31CC9C 0, #999 1, #31CC9C 2, #999 3;
.link {
  color: #406eff;
  cursor: pointer;
}
.link-container {
  width:100%;
  .delete-btn {
    color: #406EFF;
    cursor: pointer;
  }
  .sub-title-container {
    display: flex;
    align-items: center;
    margin-bottom: 9px;
    .sub-title {
      font-size: 14px;
      color: #606266;
      margin-right: 35px;
    }
    .ui-col{
      flex: 1;
    }
  }
  .not-allowed {
    cursor: not-allowed;
    color: #999;
  }
  .pagination-area{
    &::v-deep {
      .el-input__inner  {
        width: 100%;
     }
    }
  }
  &::v-deep {
    .el-input__inner  {
      width: 240px;
    }
    .el-tag--info {
      max-width: 100%;
      color: #406EFF;
      background-color: #ecf1ff;
      display: flex;
      align-items: center;
      .el-select__tags-text {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        padding-right: 3px;
      }
      .el-tag__close {
        flex-shrink: 0;
        right: 0;
        top: 1px;
      }
    }
  }
}
.empty-container {
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #EBEEFD;
  padding: 12px 0 18px 0;
  .empty-box {
    display: flex;
    align-items: center;
  }
  img {
    width: 12px;
    margin-right: 4px;
  }
  .empty-text {
    color: #999;
    font-size: 14px;
    margin: 0 auto;
  }
}
.invoice-status-0, .invoice-status-1, .invoice-status-2, .invoice-status-3 {
  position: relative;
  &::before {
    content: '';
    width: 4px;
    height: 4px;
    position: absolute;
    left: -8px;
    top: 8px;
    border-radius: 50%;
  }
}
.invoice-status-0 {
  &::before {
    background-color: #FD8546;
  }
}
.invoice-status-1 {
  &::before {
    background-color: green;
  }
}
.invoice-status-2 {
  &::before {
    background-color: red;
  }
}
.invoice-status-3 {
  &::before {
    background-color: #999;
  }
}
.dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin-right: 5px;
  @each $c, $i in $state {
    &.color-state-#{$i} {
      background: $c;
    }
  }
}
</style>
